package com.zhulanhua.blogs.filter;

import com.zhulanhua.blogs.Utils.Code;
import com.zhulanhua.blogs.Utils.TokenUtils;
import com.zhulanhua.blogs.dao.UserDao;
import com.zhulanhua.blogs.exception.TokenAuthExpiredException;
import com.zhulanhua.blogs.service.LoginService;
import com.zhulanhua.blogs.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@Slf4j
@Component
public class AuthHandlerInterceptor implements HandlerInterceptor {
    @Autowired
    TokenUtils tokenUtil;
    @Value("${token.privateKey}")
    private String privateKey;
    @Value("${token.yangToken}")
    private Long yangToken;
    @Value("${token.oldToken}")
    private Long oldToken;

    @Autowired
    LoginService loginService;

    /**
     * 权限认证的拦截操作.
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        log.info("=======进入拦截器========");
        //获取请求类型
        String method = httpServletRequest.getMethod();
        // 如果不是映射到方法直接通过,可以访问资源.并且放行所有get请求
        if (!(object instanceof HandlerMethod) || method.equals("GET")) {
            return true;
        }
        //为空就返回错误
        String token = httpServletRequest.getHeader("token");
        if (null == token || "".equals(token.trim())) {
            throw new TokenAuthExpiredException(Code.TOKEN_ERR, "未登录，请先登陆");
        }
        log.info("==============token:" + token);
        Map<String, String> map = tokenUtil.parseToken(token);
        httpServletRequest.setAttribute("token", map);
        String userId = map.get("userId");
        String userRole = map.get("userRole");
        long timeOfUse = System.currentTimeMillis() - Long.parseLong(map.get("timeStamp"));
        //1.判断 token 是否过期
        if (loginService.isLoginTime(new Date(Long.parseLong(map.get("timeStamp"))))){
            throw new TokenAuthExpiredException("其他设备登陆了你的账户，请重新登陆");
        }
        //年轻 token
        if (timeOfUse < yangToken) {
            log.info("年轻 token");
        }
        //老年 token 就刷新 token
        else if (timeOfUse >= yangToken && timeOfUse < oldToken) {
            httpServletResponse.setHeader("token",tokenUtil.getToken(userId,userRole));
        }
        //过期 token 就返回 token 无效.
        else {
            throw new TokenAuthExpiredException("登陆已过期，请重新登陆");
        }
        //2.角色匹配.
        if ("user".equals(userRole)) {
            log.info("========user账户============");
            return true;
//            throw new TokenAuthExpiredException(Code.TOKEN_ERR, "权限不够");
        }
        if ("admin".equals(userRole)) {
            log.info("========admin账户============");
            return true;
        }
        throw new TokenAuthExpiredException(Code.TOKEN_ERR, "权限异常");
    }

}

